﻿#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion

namespace Snake.Cache
{
    /// <summary>
    /// 线程安全的cache
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class DataCache<TKey, TValue>
    {
        readonly Object syncRoot = new Object();
        Dictionary<TKey, LazyInit<TValue>> cacheDictionary = new Dictionary<TKey, LazyInit<TValue>>();

        /// <summary>
        /// 取数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="producer"></param>
        /// <returns></returns>
        public TValue Fetch(TKey key, Func<TValue> producer)
        {

            LazyInit<TValue> cacheItem;

            lock (syncRoot)
            {
                if (!cacheDictionary.TryGetValue(key, out cacheItem))
                {
                    cacheItem = new LazyInit<TValue>(producer);
                    cacheDictionary.Add(key, cacheItem);
                }
            }
            return cacheItem.Value;

        }

    }
}